#include "precompiled.h"
#include "FileReader.h"

namespace IcyCrystal {


	FileReader::FileReader(void){
		buffer = NULL;
		currentPosition = 0;
		fileLength = 0;
		currentLine = 1;
	}


	FileReader::~FileReader(void) {
		delete [] buffer;
	}

	void FileReader::readFile(const string& filename) {
		this->filename = filename;
		ifstream inFile;
		// Set the exceptions

		//inFile.exceptions( ifstream::badbit || ifstream::failbit );

		inFile.open(filename.c_str(), ifstream::in);
		inFile.seekg(0, ios::end );
		fileLength = (unsigned int)inFile.tellg();
		inFile.seekg(0, ios::beg);

		buffer = new char[fileLength];

		memset(buffer,0, fileLength);
		
		inFile.read(buffer, fileLength);

		inFile.close();
	}

	char FileReader::next(){
		if( currentPosition < fileLength ){
			char& c = buffer[currentPosition++];
			if( c == '\n' )
				currentLine++;
			return c;
		}
		else
			return 0;
	}
	
	char FileReader::peek(){
		if( currentPosition + 1 < fileLength ){
			return buffer[currentPosition + 1];
		}
		else
			return 0;
	}

	char FileReader::prev() {
		if( currentPosition > 0 ){
			char& c = buffer[--currentPosition];
			if( c == '\n' )
				currentLine--;
			return c;
		}
		else
			return 0;
	}

	void FileReader::setPosition(unsigned int x){
		currentPosition = x;
	}

	unsigned int FileReader::getPosition(){
		return currentPosition;
	}

	unsigned int FileReader::getCurrentLine(){
		return currentLine;
	}


}